/*
* 项目详情
* */
import React from "react";
import {inject, observer} from "mobx-react";
import {withRouter, Route} from "react-router-dom";
import {
    Echarts,
    Icon,
    Tools,
    ActionSheet,
    SearchBar,
    Modal,
    Bubble,
    Button,
    ActivityIndicator,
    DatePicker,
    List,
    Progress
} from "weaver-mobile";
import {Form, TabPage, ListViewPage, RouteLayout, ListPage} from "weaver-mobile-page";
import {getRouteParams, openLink} from "../../util";
import ReplyEditor from "../reply/replyEditor";
import * as Tm from "../template";

const getLabel = Tools.getLabel;

const isIPhone = new RegExp("\\biPhone\\b|\\biPod\\b", "i").test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
    wrapProps = {
        onTouchStart: e => e.preventDefault(),
    };
}
@withRouter
@inject("projectDetailsStore")
@observer
export default class ProjectDetails extends React.Component {
    constructor(props) {
        super(props);
        this.state = {};
    }

    componentWillMount() {
        this.Init(this.props);
    }

    componentWillReceiveProps(nextProps, nextContext) {
        if (nextProps.match.params.prjid !== this.props.match.params.prjid ||
            nextProps.match.params.index !== this.props.match.params.index ||
            nextProps.match.params.viewtype !== this.props.match.params.viewtype) {
            this.Init(nextProps);
        }
    }

    Init = (props) => {
        const {projectDetailsStore} = props;
        const {index, prjid, viewtype} = getRouteParams(props);
        projectDetailsStore.init(index, prjid, viewtype)
    };
    static handle_Echarts_Y_Texts = (params) => {
        let newParamsName = "";// 最终拼接成的字符串
        if (params) {
            if (params.length > 11) {
                params = params.substring(0, 11) + "…";
            }

            const paramsNameNumber = params.length;// 实际标签的个数
            const provideNumber = 4;// 每行能显示的字的个数
            const rowNumber = Math.ceil(paramsNameNumber / provideNumber);// 换行的话，需要显示几行，向上取整
            /**
             * 判断标签的个数是否大于规定的个数， 如果大于，则进行换行处理 如果不大于，即等于或小于，就返回原标签
             */
            // 条件等同于rowNumber>1
            if (paramsNameNumber > provideNumber) {
                /** 循环每一行,p表示行 */
                for (let p = 0; p < rowNumber; p++) {
                    let tempStr = "";// 表示每一次截取的字符串
                    const start = p * provideNumber;// 开始截取的位置
                    const end = start + provideNumber;// 结束截取的位置
                    // 此处特殊处理最后一行的索引值
                    if (p === rowNumber - 1) {
                        // 最后一次不换行
                        tempStr = params.substring(start, paramsNameNumber);
                    } else {
                        // 每一次拼接字符串并换行
                        tempStr = params.substring(start, end) + "\n";
                    }
                    newParamsName += tempStr;// 最终拼成的字符串
                }
            } else {
                // 将旧标签的值赋给新标签
                newParamsName = params;
            }
        }
        return newParamsName
    }
    showActionSheet = () => {
        const {projectDetailsStore: {prjid, rightMenus, deleteCard, changeStateTo, tabIndex, add_edit_Stage, triggerBreakDownWF}, history} = this.props;
        const {btn_edit, btn_onFinish, btn_onFrozen, btn_onNormal, btn_onOver, btn_add, btn_delete, btn_onSubmit, btn_onApprove, btn_breakdown,menulabels} = rightMenus;
        const BUTTONS = [{
            content: getLabel("31129", "取消")
        }];
        if (btn_onFinish) {
            BUTTONS.unshift({
                content: menulabels.btn_onFinish, onClick: () => {
                    changeStateTo("complete")
                }
            });
        }
        if (btn_onFrozen) {
            BUTTONS.unshift({
                content: menulabels.btn_onFrozen, onClick: () => {
                    changeStateTo("freeze")
                }
            });
        }
        if (btn_onNormal) {
            BUTTONS.unshift({
                content: menulabels.btn_onNormal, onClick: () => {
                    changeStateTo("normal")
                }
            });
        }
        if (btn_onOver) {
            BUTTONS.unshift({
                content: menulabels.btn_onOver, onClick: () => {
                    changeStateTo("delay")
                }
            });
        }

        if (btn_onSubmit) {
            BUTTONS.unshift({
                content: getLabel("15143", "提交审批"), onClick: () => {
                    changeStateTo("submitplan")
                }
            });
        }
        if (btn_onApprove) {
            BUTTONS.unshift({
                content: getLabel("83909", "提交执行"), onClick: () => {
                    changeStateTo("approveplan")
                }
            });
        }
        if (btn_delete) {
            BUTTONS.unshift({
                content: getLabel("91", "删除"), onClick: () => {
                    deleteCard(history)
                }
            });
        }
        if (btn_edit && tabIndex !== 1) {
            BUTTONS.unshift({
                content: getLabel("26473", "编辑"), onClick: () => {
                    history.push(`/FormOperations?prjid=${prjid}&viewtype=edit`);
                }
            });
        }
        if (btn_add) {
            BUTTONS.unshift({
                content: getLabel("1421", "新增"), onClick: () => {
                    if (tabIndex === 1) {
                        add_edit_Stage(history)
                    } else if (tabIndex === 2) {
                        history.push(`/FormOperations?parentid=prj&prjid=${prjid}&viewtype=add`);
                    }
                }
            });
        }
        if (btn_breakdown) {
            BUTTONS.unshift({
                content: getLabel("512886", "任务分解1"), onClick: () => {
                    triggerBreakDownWF();
                }
            });
        }
        ActionSheet.showActionSheetWithOptions({
            options: BUTTONS,
            cancelButtonIndex: BUTTONS.length - 1,
            maskClosable: true,
            "data-seed": "logId",
            wrapProps,
        });
    };


    render() {
        const {
            history,
            projectDetailsStore: {
                tabIndex, onTabChange, PrjTaskList, prjid, layout, stageForm, saveStage, setPage,
                echartsOptions, RelativeDocList, docSearchVal, changeSearchValue, rightMenus, Toasting,
                echartsOptions: {mindate}, getRelativeDocList, isLoading, hasRight, comment
            }
        } = this.props;

        const option = {
            title: {
                text: "",
                x: "right"
            },
            tooltip: {
                trigger: "axis",
                axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                    type: "shadow"        // 默认为直线，可选为：'line' | 'shadow'|'cross
                },
                position: function (pos, params, el, elRect, size) {    //计算弹出层位置，保持不同屏幕下，弹出层始终处于屏幕内
                    let obj = {}, padd = size.viewSize[0] / 2 - 30;
                    obj[["left", "right"][+(pos[0] < size.viewSize[0] / 2)]] = padd;    //根据点击处于屏幕左侧还是右侧，来向obj添加right还是left属性
                    if (size.viewSize[0] - (padd + el.clientWidth) < 1) {   //如果el宽度加一边边距大于屏幕宽度
                        delete obj[["left", "right"][+(pos[0] < size.viewSize[0] / 2)]];    //删除边距
                        obj[["left", "right"][+(pos[0] > size.viewSize[0] / 2)]] = 1;       //重设反向边距为1
                    }
                    obj["top"] = Math.max(pos[1] - 113, -10);   //设定弹出层y坐标，不超出顶部
                    return obj;
                },
                formatter: function (params) {
                    let relVal = params[0].axisValueLabel;
                    const getDateStr = (hideBar, dataBar) => {
                        let str = "";
                        str += new Date(new Date(echartsOptions.mindate).getTime() + (86400000) * Number(hideBar.value)).Format("yyyy-MM-dd") +
                            " " + getLabel("15322", "至") + " " + new Date(new Date(echartsOptions.mindate).getTime() + (86400000) * (Number(hideBar.value) + Number(dataBar.value))).Format("yyyy-MM-dd");
                        return str;
                    };
                    relVal += "<br/>" + getLabel("407", "计划") + "：" + getDateStr(params[0], params[1]) + "<br/>" + getLabel("628", "实际") + "：" + getDateStr(params[2], params[3]);
                    return relVal;
                }
            },
            legend: {
                data: [getLabel("407", "计划"), getLabel("628", "实际")], x: 30
            },
            toolbox: {
                show: false, //是否显示工具栏
                feature: {
                    mark: {show: false},
                    dataView: {
                        show: true,//显示数据视图
                        optionToContent: function (opt) {
                            const axisData = opt.yAxis[0].data;
                            const series = opt.series;
                            let table = "<table style=\"width:100%;text-align:center\"><tbody><tr>"
                                + "<td>" + getLabel("1332", "任务") + "</td>" + "<td>" + series[1].name + "</td>"
                                + "<td>" + series[3].name + "</td>"
                                + "</tr>";
                            for (let i = 0, l = axisData.length; i < l; i++) {
                                table += "<tr>"
                                    + "<td>" + axisData[i] + "</td>"
                                    + "<td>" + series[1].data[i] + "</td>"
                                    + "<td>" + series[3].data[i] + "</td>"
                                    + "</tr>";
                            }
                            table += "</tbody></table>";
                            return table;
                        }
                    },
                    restore: {show: false},
                    saveAsImage: {show: true}
                }
            },
            grid: {
                left: "2%",
                right: "8%",
                bottom: "3%",
                containLabel: true
            },
            yAxis: {
                type: "category",
                inverse: true,
                splitLine: {show: false},
                data: echartsOptions.names,
                axisLabel: {
                    color: "#000",
                    interval: 0,
                    fontSize: 12,
                    formatter: (params) => ProjectDetails.handle_Echarts_Y_Texts(params)
                },
            },
            xAxis: {
                type: "value",
                boundaryGap: [0, 0.01],
                axisLabel: {
                    show: true,
                    interval: 0,
                    formatter: (value) => new Date(new Date(echartsOptions.mindate).getTime() + (86400000) * value).Format("MM-dd")    //86400000，一天的毫秒数
                }
            }
            ,
            series: [
                {
                    name: "planDate",
                    type: "bar",
                    stack: "plan",
                    barCategoryGap: "10%",
                    itemStyle: {
                        normal: {
                            borderColor: "rgba(0,0,0,0)",
                            color: "rgba(0,0,0,0)"
                        },
                        emphasis: {
                            borderColor: "rgba(0,0,0,0)",
                            color: "rgba(0,0,0,0)"
                        }
                    },
                    // data: [0.9, 160, 67, 112, 148, 179, 160, 67, 112, 148, 179]   //计划的起始位置
                    data: echartsOptions.begindate   //计划的起始位置
                },
                {
                    name: getLabel("407", "计划"), type: "bar",
                    stack: "plan",
                    itemStyle: {
                        normal: {
                            label: {
                                show: true,
                                position: "right",
                                textStyle: {
                                    fontSize: 14
                                },
                                formatter: function (obj) {
                                    return obj.value;
                                }
                            },
                            color: "#f4333c"
                        }
                    },
                    // data: [50, 0.1, 1.9, 50, 50, 50, 50, 50, 50, 50, 50]		//计划的数据内容
                    data: echartsOptions.workday		//计划的数据内容
                },
                {
                    name: "factDate",
                    type: "bar",
                    stack: "fact",
                    itemStyle: {
                        normal: {
                            borderColor: "rgba(0,0,0,0)",
                            color: "rgba(0,0,0,0)"
                        },
                        emphasis: {
                            borderColor: "rgba(0,0,0,0)",
                            color: "rgba(0,0,0,0)"
                        }
                    },
                    // data: [0, 160, 67, 112, 148, 179, 160, 67, 112, 148, 179]   //实际进度的起始位置
                    data: echartsOptions.actualdate   //实际进度的起始位置
                },
                {
                    name: getLabel("628", "实际"), type: "bar",
                    stack: "fact",
                    itemStyle: {
                        normal: {
                            label: {
                                show: true,
                                position: "right",
                                textStyle: {
                                    fontSize: 14
                                },
                                formatter: function (obj) {
                                    return obj.value;
                                }
                            },
                            color: "#91c7ae"
                        }
                    },
                    // data: [50.9, 16, 60, 22, 58, 96, 16, 60, 22, 58, 96]   //实际进度行数据内容
                    data: echartsOptions.realmanday  //实际进度行数据内容
                }, {
                    name: "none",
                    type: "bar",
                    stack: "none",
                    barWidth: "2",
                    itemStyle: {
                        normal: {
                            borderColor: "rgba(0,0,0,0)",
                            color: "rgba(0,0,0,0)"
                        },
                        emphasis: {
                            borderColor: "rgba(0,0,0,0)",
                            color: "rgba(0,0,0,0)"
                        }
                    },
                    data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                }
            ]
        }
        const tabPageConf = {
            tabs: [
                {title: getLabel("81711", "基本信息"), index: 0},
                {title: getLabel("24902", "阶段"), index: 1},
                {title: getLabel("1332", "任务"), index: 2},
                {title: getLabel("15153", "相关交流"), index: 3},
                {title: getLabel("857", "相关文档"), index: 4},
                {title: getLabel("18820", "甘特图"), index: 5}],
            btns: [<Icon type="ellipsis" onClick={this.showActionSheet.bind(this)}/>],
            props: {
                onChange: (tab) => onTabChange(tab.index, history),
                initialPage: 0,     //初始化tab
                page: tabIndex//当前tab
            }
        }
        return (
            <div className='tab-page-wrapper'>
                {!hasRight ?
                    <div className="no-right-page">
                        <Bubble.Bubble
                            type={12}
                            propmt={getLabel("2012", "对不起，您暂时没有权限！")}/>
                    </div>
                    :
                    <div style={{height: "100%"}}>
                        <TabPage
                            className='proj-tab-page'
                            tabs={tabPageConf.tabs}
                            btns={JSON.stringify(rightMenus) !== "{}" ? tabPageConf.btns : []}
                            tabProps={tabPageConf.props}
                        />
                        <div className="proj-details-info-wrapper">
                            {tabIndex === 0 ?
                                <div>
                                    {isLoading ?
                                        (<div className='loading'><ActivityIndicator animating size='large'/></div>) :
                                        <Form style={{height: "100%"}}>
                                            <List className="prj-self-form prj-data-picker-css-style">
                                                {this.renderForm()}
                                            </List>
                                        </Form>}
                                </div> : null}
                            {tabIndex === 1 ? <div>
                                <Route
                                    key={layout.id}
                                    path={layout.path}
                                    render={() => (
                                        <RouteLayout>
                                            <div
                                                key="wmPoutePageDemo"
                                                className="wm-route-layout"
                                            >
                                                <Form store={stageForm}/>
                                                <div className="proj-button-group">
                                                    <Button type="ghost" className='proj-button-cancel' onClick={() => {
                                                        history.go(-1)
                                                    }}>{getLabel("31129", "取消")}</Button>
                                                    <Button type="primary" className='proj-button-apply'
                                                            disabled={Toasting}
                                                            onClick={() => {
                                                                saveStage(history)
                                                            }}>{getLabel("30986", "保存")}</Button>
                                                </div>
                                            </div>
                                        </RouteLayout>
                                    )}
                                />
                                <List>
                                    {this.PrjStateListRender()}
                                </List>
                                {/*    <ListViewPage.Normal
                                    rowKey="id"
                                    store={PrjStateList}
                                    heightSpace={window.getThemeVars ? window.getThemeVars()["tab-bar-height"] : 50}
                                    getTemplate={Tm.getPrjStateTemplate}
                                    withSwipeAction={true}
                                    swipeActionProps={{
                                        autoClose: true,
                                        right: [{
                                            text: getLabel("26473", "编辑"),
                                            style: {backgroundColor: "#4dacfa", color: "#fff", padding: "0 8px"},
                                            onPress: (data) => {
                                                add_edit_Stage(history, data.id)
                                            },
                                        }, {
                                            text: getLabel("91", "删除"),
                                            style: {backgroundColor: "#f4333c", color: "#fff", padding: "0 8px"},
                                            onPress: (data) => {
                                                if (data["candelspan"] !== "true") {
                                                    Bubble.error(getLabel("500812", "该阶段在任务中已经使用，不能删除！"), 1);
                                                    return
                                                }
                                                Modal.alert(getLabel("15172", "系统提示"), getLabel("500813", "确定删除该阶段吗？"), [{
                                                    text: getLabel("31129", "取消")
                                                },
                                                    {
                                                        text: getLabel("826", "确定"), onPress: () => {
                                                            deleteStage(history, data.id)
                                                        }
                                                    }])
                                            },
                                        }]
                                    }}
                                />*/}
                            </div> : null}
                            {tabIndex === 2 ? <div>
                                <ListViewPage.Normal
                                    rowKey="id"
                                    store={PrjTaskList}
                                    heightSpace={window.getThemeVars ? window.getThemeVars()["tab-bar-height"] : 50}
                                    getTemplate={Tm.getPrjChildTaskListTemplate}
                                    onRowClick={(item) => {
                                        history.push(`/TaskDetails/0/${item.id}`);
                                    }}
                                />
                            </div> : null}

                            {tabIndex === 3 ? <div style={{height: "100%"}}>
                                <ReplyEditor replyStore={comment}
                                             sortid={prjid}
                                             discusstype="PP"
                                             onReload={(page = 1) => {
                                                 setPage(page)
                                             }}/>
                            </div> : null}

                            {tabIndex === 4 ? <div>
                                <SearchBar
                                    className="search-select"
                                    placeholder="Search"
                                    value={docSearchVal}
                                    onChange={(val) => changeSearchValue(val)}
                                    onSubmit={() => getRelativeDocList()}
                                    onClear={() => {
                                        changeSearchValue();
                                        getRelativeDocList();
                                    }}
                                />
                                <div>
                                    <ListViewPage.Normal
                                        rowKey="id"
                                        heightSpace={window.getThemeVars ? window.getThemeVars()["tab-bar-height"] : 50}
                                        store={RelativeDocList}
                                        getTemplate={Tm.getDocumentTemplate}
                                        onRowClick={(item) => {
                                            openLink("doc", item.docid)
                                        }}
                                    />
                                </div>
                            </div> : null}
                            {tabIndex === 5 && mindate ?
                                <div className="proj-echarts-wrapper-gante"
                                     style={{height: document.documentElement.clientHeight * 0.8}}>
                                    {isLoading ?
                                        (<div className='loading'><ActivityIndicator animating size='large'/></div>)
                                        :
                                        <Echarts option={option}/>
                                    }
                                </div>
                                : null}
                        </div>
                    </div>}
            </div>)
    }

    PrjStateListRender = () => {
        const {projectDetailsStore: {PrjStateList, rightMenus}} = this.props;
        const fields = [];
        PrjStateList.data.forEach((item, index) => {
            fields.push(<ListPage.Item
                key={index}
                data={item}
                getTemplate={Tm.getPrjStateTemplate}
                withSwipeAction={(item["candelspan"] && item["candelspan"] !== "false") || (rightMenus["btn_add"])}//存在编辑或删除
                swipeActionProps={this.swipeRight(item)}
            />);
        });
        return fields;
    }

    swipeRight = (item) => {
        const {projectDetailsStore: {add_edit_Stage, deleteStage, rightMenus}, history} = this.props;
        const res = {right: []};
        if (rightMenus["btn_add"]) {
            res.right.push({
                text: getLabel("26473", "编辑"),
                style: {backgroundColor: "#4dacfa", color: "#fff", padding: "0 8px"},
                onPress: (data) => {
                    add_edit_Stage(history, data.id)
                },
            })
        }
        if (item["candelspan"] && item["candelspan"] !== "false") {
            res.right.push({
                text: getLabel("91", "删除"),
                style: {backgroundColor: "#f4333c", color: "#fff", padding: "0 8px"},
                onPress: (data) => {
                    if (data["candelspan"] !== "true") {
                        Bubble.error(getLabel("500812", "该阶段在任务中已经使用，不能删除！"), 1);
                        return
                    }
                    Modal.alert(getLabel("15172", "系统提示"), getLabel("500813", "确定删除该阶段吗？"), [{
                        text: getLabel("31129", "取消")
                    },
                        {
                            text: getLabel("826", "确定"), onPress: () => {
                                deleteStage(history, data.id)
                            }
                        }])
                },
            })
        }
        return res;
    }
    renderForm = () => {
        const {form, formChange, linkToAccessory} = this.props.projectDetailsStore;
        const {conditioninfo, isInit} = form;
        const fields = [];
        if (isInit) {
            let accessoryContents = [];
            conditioninfo.forEach((group) => {
                group.items.forEach((field) => {
                    if (field.conditionType === "PRJDATETIME") {
                        fields.push(<DatePicker
                            style={{textAlign: "center"}}
                            key={field.domkey.join("__")}
                            value={field.value[0] === "" ? "" : (field.value[1] === "" ? [field.value[0], field.value[1]].join(" ") + "00:00" : [field.value[0], field.value[1]].join(" "))}
                            extra={<span/>}
                            disabled
                        >
                            <List.Item arrow="horizontal">{field.label}</List.Item>
                        </DatePicker>)
                    } else if (field.domkey[0] === "finish") {
                        fields.push(
                            <List className="my-list" key={field.domkey.join("__")}>
                                <List.Item extra={
                                    <div className="proj-show-info">
                                        <div className="progress"><Progress percent={field.value} position="normal"/>
                                        </div>
                                        <div aria-hidden="true"><span className="progress-text">{field.value}%</span>
                                        </div>
                                    </div>
                                }>{field.label}</List.Item>
                            </List>)
                    } else {
                        fields.push(<Form.Item
                            key={field.domkey.join("__")}
                            form={form}
                            fieldConfig={field}
                            onChange={() => [formChange(field)]}
                        />);
                    }

                });
            });
        }
        return fields;
    }

}

Date.prototype.Format = function (fmt) {
    let o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (let k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
